<?php
namespace app\common\netfilter;

use app\common\exception\CustomException;
use app\common\service\HostContact;
use app\common\service\module_manage\netfilter\HostLearnConfig;
use think\Db;

class Rule 
{
    private $osRule;

    /**
     * @name: 选择 规则内容
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-11-12 15:57:31
     */
    public function change ($operation_system)
    {
        switch ($operation_system) {
            case 1 :
                $this->osRule = new Windows2008Rule();
                break;
            case 2 :
                $this->osRule = new LinuxRule();
                break;
            default :
                throw new CustomException('系统未知!', 302);
        }
    }

    /**
     * @name:  防火墙规则
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-11-12 16:08:27
     */
    public function firewallRule ($data, $os)
    {

        if (empty($data))
        {
            return [];
        }

        $return = [];
        $this->change($os);
        $method = get_class_methods($this->osRule);
        
        $src_ip_a = explode(',', $data['src_ip']);
        $dest_ip_a = explode(',', $data['dest_ip']);
        foreach($src_ip_a as $src_ip)
        {
            $data['src_ip'] = $src_ip;
            foreach ($dest_ip_a as $dest_ip)
            {
                $data['dest_ip'] = $dest_ip;
                $data['alias'] = 'asmp_'. $data['alias'] . '_' . md5($data['src_ip'] . '-' . $data['src_port'] . '-' . $data['dest_ip'] . '-' . $data['dest_port'] . '-' . $data['protocols']);
                $return[] = $this->creatRuleStr($method, $data);
            }
        }

        return $return;
    }

    /**
     * @name: 创建规则 字符
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-02 17:47:32
     */
    public function creatRuleStr ($method, $ruleData)
    {
        $return = $this->osRule->rulehead;
        $this->osRule->protocols = $ruleData['protocols'];
        foreach ($method as $cv)
        {
            if($cv == 'ip' || $cv == 'port')
            {
                $tmp =  [$ruleData['src_' . $cv],$ruleData['dest_' . $cv]];
            }
            else
            {
                if(isset($ruleData[$cv]))
                {
                    $tmp = [$ruleData[$cv]];
                }
                else
                {
                    $tmp = [];
                }
            } 
            $return .= ' ';
            $return .= call_user_func_array([$this->osRule, $cv], $tmp);
        }
        $return = trim(preg_replace('/\s{2,}/i', ' ', $return));
        return $return;
    }
}